package com.lihh.rocket5.normal;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.io.UnsupportedEncodingException;
import java.util.List;

public class TagFilterConsumer {
  public static void main(String[] args) throws MQClientException {
    // 拿到 consumer 实例
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_group_004");
    // 设置 consumer  name server
    consumer.setNamesrvAddr("localhost:9876");
    // 设置消费主题
    consumer.subscribe("order005", "A || B");
    // 设置消费位置
    consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
    
    consumer.registerMessageListener(new MessageListenerConcurrently() {
      @Override
      public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        for (MessageExt msg : list) {
          String topic = msg.getTopic();
          String tags = msg.getTags();
          try {
            String message = new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET);
            System.out.println(String.format("topic: %s, tags: %s, message: %s", topic, tags, message));
          } catch (UnsupportedEncodingException e) {
//            throw new RuntimeException(e);
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
          }
          
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
      }
    });
    
    consumer.start();
    while (true) {
    }
  }
}
